import { getSongById, getAllSongs, type Song } from '../../utils/api';
import { getAudio, playSong, pause, getState, setSeek } from '../../utils/audio';

Component({
  data: {
    song: {} as Song,
    index: 0,
    paused: true,
    currentTime: 0,
    duration: 0
  },
  lifetimes: {
    attached() {
      const query = this.getPageQuery();
      const songId = query.id || '';
      const list = getAllSongs();
      const idx = Math.max(0, list.findIndex(s => s.id === songId));
      const song = getSongById(songId) || list[0];
      this.setData({ song, index: idx });
      const a = getAudio();
      a.offTimeUpdate();
      a.onTimeUpdate(() => {
        const state = getState();
        this.setData({ currentTime: state.currentTime, duration: state.duration, paused: state.paused });
      });
      a.offEnded();
      a.onEnded(() => this.next());
      this.play();
    }
  },
  methods: {
    getPageQuery(): any {
      // @ts-ignore
      const pages = getCurrentPages();
      const current = pages[pages.length - 1];
      return (current as any).options || {};
    },
    play() {
      playSong(this.data.song, () => this.next());
      this.setData({ paused: false });
    },
    pause() {
      pause();
      this.setData({ paused: true });
    },
    onPlayPause() {
      if (this.data.paused) this.play();
      else this.pause();
    },
    onPrev() {
      const list = getAllSongs();
      let index = this.data.index - 1;
      if (index < 0) index = list.length - 1;
      const song = list[index];
      this.setData({ index, song });
      this.play();
    },
    onNext() {
      this.next();
    },
    next() {
      const list = getAllSongs();
      let index = this.data.index + 1;
      if (index >= list.length) index = 0;
      const song = list[index];
      this.setData({ index, song });
      this.play();
    },
    onSeek(e: any) {
      const value = Number(e.detail.value || 0);
      setSeek(value);
    },
    formatTime(sec: number) {
      const s = Math.floor(sec || 0);
      const m = Math.floor(s / 60);
      const r = s % 60;
      return `${m}:${r < 10 ? '0' + r : r}`;
    }
  }
});